import { Component, OnInit, Output, Input, EventEmitter } from '@angular/core';
import { UserService } from 'src/app/service/user.service';
import { BaseService } from 'src/app/service/base.service';
import { UtilsService } from 'src/app/service/utils.service';
import type { Subscription } from 'rxjs';
import * as dayjs from 'dayjs';
@Component({
  selector: 'app-date-picker',
  templateUrl: './date-picker.component.html',
  styleUrls: ['./date-picker.component.scss'],
})
export class DatePickerComponent implements OnInit {
  @Input() timeConfig: any[] = [];
  @Input() type: number | string;
  @Output() change = new EventEmitter<EndYear.Renqi.IDailyTabItem>();
  /* ___ _ ___ */
  public deployUrl: string;
  private reshing: Subscription = null; /* 订阅刷新 */
  /* ___ _ ___ */
  public tabs: EndYear.Renqi.IDailyTabItem[] = [];
  public activeIndex: number = 0; /* 当前选中序号 */
  private readonly SECTION_GAP = 4; /* 每组显示几个日期 */
  private SECTION_WIDTH = 6.08; /* 区间宽度 */
  public sectionCounts: number = undefined;
  public wrapperStyle = `left:0;`;
  public curRound: number = 1; /* 第几轮 */

  constructor(
    private userService: UserService,
    private baseService: BaseService,
    private utilsService: UtilsService
  ) {}

  ngOnInit() {
    // 获取
    this.deployUrl = this.userService.getDeployUrl();

    // 初始化
    this.initDates();
    // 组件刷新通信
    this.reshing = this.utilsService.MsgSub.subscribe(() => {
      this.initDates();
    });
  }

  ngOnDestroy(): void {
    /* 取消订阅 */
    if (this.reshing) this.reshing.unsubscribe();
  }

  /**
   * @description: 获取需要渲染的日期组
   */
  initDates() {
    const configs = this.timeConfig;
    // console.log('configs=>', configs, this.type);
    //本地配置的模拟数据方便调试
    // const fake = [
    //   {
    //     id: 1,
    //     startTime: 1669136400000, //2022/11/23 1:00:00
    //     endTime: 1669219199000, //2022/11/23 1:00:00
    //     type: 20,
    //   },
    //   {
    //     id: 2,
    //     startTime: 1669222861000, //2022/11/24 1:00:00
    //     endTime: 1669302061000, //2022/11/24 23:00:00
    //     type: 20,
    //   },
    //   {
    //     id: 411,
    //     startTime: 1669309261000, //2022/11/25 1:00:00
    //     endTime: 1669388461000, //2022/11/25 23:00:00
    //     type: 20,
    //   },
    //   {
    //     id: 415,
    //     startTime: 1669395661000, //2022/11/26 1:00:00
    //     endTime: 1669474861000, //2022/11/26 23:00:00
    //     type: 20,
    //   },
    //   {
    //     id: 5,
    //     startTime: 1669482061000, //2022/11/27 1:00:00
    //     endTime: 1669561261000, //2022/11/27 23:00:00
    //     type: 20,
    //   },
    // ];
    // 获取当前日榜的所有configs
    const validConfigs = configs
      .filter((config) => config.type === +this.type)
      .sort((i, j) => i.startTime - j.startTime); /* 开始时间 小到大 */

    // 生成渲染数组
    const tabs = validConfigs.map((config) => {
      const { startTime, endTime, id, name: configAlias } = config;
      /* 某月某日 */
      const { status } = this.useDateStatus(
        startTime * 1000,
        endTime * 1000,
        configAlias /* TOLOG */
      );
      return {
        id,
        name: this.transformTimestampToString(
          startTime * 1000
        ) /* 接口时间单位为s */,
        status,
      };
    });

    console.table(tabs);

    this.tabs = tabs;

    // 优先获取今日对应的日期序号 如果结束获取最后一个结束的日期
    let activeIndex = 0;
    for (let index = 0; index < tabs.length; index++) {
      const tab = tabs[index];
      const { status } = tab;
      /* 遇到3 往后移 除非最后一位 */
      if (status === 3 && index !== tabs.length - 1) {
        continue;
      }
      /* 遇到 1,2 直接跳出循环 */
      activeIndex = index;
      break;
    }

    console.log('activeIndex=>', activeIndex);
    // const todayIndex = tabs.findIndex((item) => item.status === 2);
    // const defaultIndex = todayIndex > -1 ? todayIndex : 0;

    this.activeIndex = activeIndex;
    this.curRound = Math.ceil((activeIndex + 1) / this.SECTION_GAP);
    this.sectionCounts = Math.ceil(tabs.length / this.SECTION_GAP); /* 总组数 */
    console.log('11=>', activeIndex, this.curRound, this.sectionCounts);

    // console.log('日期处理=>', tabs, defaultIndex);
    const defaultTab = this.tabs[this.activeIndex];
    this.change.emit(defaultTab);
    this.wrapperStyle = `left:-${
      (this.curRound - 1) * this.SECTION_WIDTH
    }rem;)`;
  }

  /**
   * @param timestamp
   * @description: 时间戳 转换为 12月1日
   */
  transformTimestampToString(timestamp: number): string {
    /* 部分浏览器出现的 格式不一致 改用dayjs */
    // const localString = new Date(
    //   timestamp
    // ).toLocaleDateString(); /* '2022/11/25' */
    const localString = dayjs(timestamp).format('YYYY/MM/DD'); // '2019/01/25/01'
    console.log('new localString=>', localString);
    const [, month, day] = localString.split('/');
    return `${month}月${day}日`;
  }

  /**
   * @param timestamp
   * @description: 判断目标和当前时间的关系 1 过去 2 今日 3 明日且之后
   */
  useDateStatus(startTime, endTime, configAlias): { status: 1 | 2 | 3 } {
    const now = Date.now();

    let status;
    // 判断当前时间
    if (now < startTime) {
      // 榜单未开始
      status = 1;
      // current = false;
      console.log(`%c ${configAlias}`, 'color:#00cec9;');
      console.log(
        `未开始 : 开始时间:${new Date(
          startTime
        ).toLocaleString()} 结束时间:${new Date(endTime).toLocaleString()}`
      );
    } else if (now > endTime) {
      // 榜单已结束
      status = 3;
      // current = false;
      console.log(`%c ${configAlias}`, 'color:#00cec9;');
      console.log(`已结束 : 结束时间:${new Date(endTime).toLocaleString()}`);
    } else {
      // 榜单进行中
      status = 2;
      // current = true;
      console.log(`%c ${configAlias}`, 'color:#00cec9;');
      console.log(
        `进行中 :  开始时间:${new Date(
          startTime
        ).toLocaleString()} 结束时间:${new Date(endTime).toLocaleString()}`
      );
    }
    return { status };
  }

  /**
   * @param num 变化数 +1/-1
   * @description:
   */
  onDatePickerSelect(num: number) {
    const totalRound = Math.ceil(this.tabs.length / this.SECTION_GAP);

    if (this.curRound + num > totalRound || this.curRound + num < 1) {
      return;
    }
    this.curRound += num as 1 | -1;

    this.wrapperStyle = `left:-${
      (this.curRound - 1) * this.SECTION_WIDTH
    }rem;)`;
  }

  getDatePickerArrowActive(direction: 'left' | 'right'): boolean {
    const totalRound = Math.ceil(this.tabs.length / this.SECTION_GAP);
    let active = false;

    // console.log('getDatePickerArrowActive=>', totalRound);
    switch (direction) {
      case 'left':
        active = this.curRound > 1;
        break;
      case 'right':
        active = this.curRound < totalRound;
        break;
    }
    return active;
  }

  /**
   * @param j index
   * @description:
   */
  onTabClick(j) {
    // 判断时间线
    const target = this.tabs[j];
    if (target.status === 1) {
      // 提示未开始
      this.baseService.showToast('活动暂未开始', 1500);
      return;
    }
    // 选中
    this.activeIndex = j;
    // 发射事件
    this.change.emit(target);
    console.log('onTabClick=>', target);
  }
}
